import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { NavBar, Button, Toast, Modal, Card } from 'antd-mobile';
import { LeftOutline, CameraOutline, PictureOutline } from 'antd-mobile-icons';
import QrScanner from 'qr-scanner';
import styles from './QRScanner.module.css';

function QRScanner() {
    const navigate = useNavigate();
    const videoRef = useRef(null);
    const qrScannerRef = useRef(null);
    const fileInputRef = useRef(null);

    const [isScanning, setIsScanning] = useState(false);
    const [hasCamera, setHasCamera] = useState(false);
    const [flashOn, setFlashOn] = useState(false);
    const [scanResult, setScanResult] = useState(null);
    const [resultModalVisible, setResultModalVisible] = useState(false);
    const [permissionDenied, setPermissionDenied] = useState(false);

    // 初始化摄像头和扫描器
    useEffect(() => {
        checkCameraSupport();
        return () => {
            stopScanning();
        };
    }, []);

    // 检查摄像头支持
    const checkCameraSupport = async () => {
        try {
            const hasCamera = await QrScanner.hasCamera();
            setHasCamera(hasCamera);
            if (hasCamera) {
                startScanning();
            }
        } catch (error) {
            console.error('检查摄像头失败:', error);
            setHasCamera(false);
        }
    };

    // 开始扫描
    const startScanning = async () => {
        if (!videoRef.current) return;

        try {
            // 创建二维码扫描器
            qrScannerRef.current = new QrScanner(
                videoRef.current,
                (result) => handleScanSuccess(result.data),
                {
                    onDecodeError: (error) => {
                        // 正常情况，扫描过程中会有很多解码错误
                        console.debug('Decode error:', error);
                    },
                    highlightScanRegion: true,
                    highlightCodeOutline: true,
                    maxScansPerSecond: 5,
                }
            );

            await qrScannerRef.current.start();
            setIsScanning(true);
            setPermissionDenied(false);
        } catch (error) {
            console.error('启动扫描失败:', error);
            if (error.name === 'NotAllowedError') {
                setPermissionDenied(true);
                Toast.show({
                    content: '请允许访问摄像头以使用扫码功能',
                    icon: 'fail'
                });
            } else {
                Toast.show({
                    content: '摄像头启动失败，请检查设备',
                    icon: 'fail'
                });
            }
        }
    };

    // 停止扫描
    const stopScanning = () => {
        if (qrScannerRef.current) {
            qrScannerRef.current.stop();
            qrScannerRef.current.destroy();
            qrScannerRef.current = null;
        }
        setIsScanning(false);
        setFlashOn(false);
    };

    // 扫描成功处理
    const handleScanSuccess = (data) => {
        console.log('扫描结果:', data);
        setScanResult(data);
        setResultModalVisible(true);
        stopScanning();

        // 震动反馈（如果支持）
        if (navigator.vibrate) {
            navigator.vibrate(100);
        }
    };

    // 切换闪光灯
    const toggleFlash = async () => {
        if (qrScannerRef.current) {
            try {
                if (flashOn) {
                    await qrScannerRef.current.turnFlashOff();
                    setFlashOn(false);
                } else {
                    await qrScannerRef.current.turnFlashOn();
                    setFlashOn(true);
                }
            } catch (error) {
                Toast.show({
                    content: '闪光灯控制失败',
                    icon: 'fail'
                });
            }
        }
    };

    // 从相册选择图片扫描
    const scanFromImage = () => {
        fileInputRef.current?.click();
    };

    // 处理图片文件
    const handleImageUpload = async (event) => {
        const file = event.target.files[0];
        if (!file) return;

        try {
            const result = await QrScanner.scanImage(file);
            handleScanSuccess(result);
        } catch (error) {
            console.error('图片扫描失败:', error);
            Toast.show({
                content: '未识别到二维码，请选择清晰的二维码图片',
                icon: 'fail'
            });
        }

        // 清空文件输入
        event.target.value = '';
    };

    // 处理扫描结果
    const processScanResult = (data) => {
        // 判断二维码类型并进行相应处理
        if (data.startsWith('http://') || data.startsWith('https://')) {
            // 网址
            window.open(data, '_blank');
        } else if (data.startsWith('tel:')) {
            // 电话号码
            window.location.href = data;
        } else if (data.startsWith('mailto:')) {
            // 邮箱
            window.location.href = data;
        } else if (data.startsWith('wifi:')) {
            // WiFi信息
            Toast.show({
                content: 'WiFi信息已获取，请手动连接',
                duration: 3000
            });
        } else {
            // 普通文本
            navigator.clipboard?.writeText(data).then(() => {
                Toast.show({
                    content: '内容已复制到剪贴板',
                    icon: 'success'
                });
            }).catch(() => {
                Toast.show({
                    content: '复制失败，请手动复制',
                    icon: 'fail'
                });
            });
        }

        setResultModalVisible(false);
        setScanResult(null);
    };

    // 重新扫描
    const restartScanning = () => {
        setResultModalVisible(false);
        setScanResult(null);
        if (hasCamera) {
            startScanning();
        }
    };

    // 返回上一页
    const handleBack = () => {
        stopScanning();
        navigate(-1);
    };

    // 获取结果类型图标和描述
    const getResultInfo = (data) => {
        if (data.startsWith('http://') || data.startsWith('https://')) {
            return { icon: '🌐', type: '网址链接', action: '打开链接' };
        } else if (data.startsWith('tel:')) {
            return { icon: '📞', type: '电话号码', action: '拨打电话' };
        } else if (data.startsWith('mailto:')) {
            return { icon: '📧', type: '邮箱地址', action: '发送邮件' };
        } else if (data.startsWith('wifi:')) {
            return { icon: '📶', type: 'WiFi信息', action: '查看详情' };
        } else {
            return { icon: '📄', type: '文本内容', action: '复制内容' };
        }
    };

    return (
        <div className={styles.container}>
            {/* 导航栏 */}
            <NavBar
                onBack={handleBack}
                backIcon={<LeftOutline />}
                className={styles.navbar}
            >
                扫一扫
            </NavBar>

            {/* 扫描区域 */}
            <div className={styles.scannerContainer}>
                {hasCamera && !permissionDenied ? (
                    <>
                        <video
                            ref={videoRef}
                            className={styles.video}
                            playsInline
                            muted
                        />
                        <div className={styles.overlay}>
                            <div className={styles.scanBox}>
                                <div className={styles.corners}>
                                    <div className={`${styles.corner} ${styles.topLeft}`}></div>
                                    <div className={`${styles.corner} ${styles.topRight}`}></div>
                                    <div className={`${styles.corner} ${styles.bottomLeft}`}></div>
                                    <div className={`${styles.corner} ${styles.bottomRight}`}></div>
                                </div>
                                <div className={styles.scanLine}></div>
                            </div>
                            <div className={styles.tipText}>
                                将二维码放入框内，即可自动扫描
                            </div>
                        </div>
                    </>
                ) : (
                    <div className={styles.noCamera}>
                        <div className={styles.noCameraIcon}>📷</div>
                        <div className={styles.noCameraText}>
                            {permissionDenied ? '摄像头权限被拒绝' : '无法访问摄像头'}
                        </div>
                        <div className={styles.noCameraSubtext}>
                            {permissionDenied ? '请在浏览器设置中允许摄像头访问' : '请检查设备摄像头是否可用'}
                        </div>
                    </div>
                )}
            </div>

            {/* 控制按钮 */}
            <div className={styles.controls}>
                {isScanning && (
                              <Button
            className={`${styles.controlBtn} ${flashOn ? styles.flashOn : ''}`}
            onClick={toggleFlash}
          >
            <span style={{ fontSize: '24px' }}>💡</span>
            <span>闪光灯</span>
          </Button>
                )}

                <Button
                    className={styles.controlBtn}
                    onClick={scanFromImage}
                >
                    <PictureOutline />
                    <span>从相册选择</span>
                </Button>

                {!isScanning && hasCamera && (
                    <Button
                        color="primary"
                        className={styles.controlBtn}
                        onClick={startScanning}
                    >
                        <CameraOutline />
                        <span>重新扫描</span>
                    </Button>
                )}
            </div>

            {/* 隐藏的文件输入 */}
            <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                onChange={handleImageUpload}
                style={{ display: 'none' }}
            />

            {/* 扫描结果弹窗 */}
            <Modal
                visible={resultModalVisible}
                title="扫描结果"
                onClose={() => setResultModalVisible(false)}
                actions={[
                    {
                        key: 'cancel',
                        text: '重新扫描',
                        onClick: restartScanning
                    },
                    {
                        key: 'confirm',
                        text: scanResult ? getResultInfo(scanResult).action : '确定',
                        primary: true,
                        onClick: () => processScanResult(scanResult)
                    }
                ]}
            >
                {scanResult && (
                    <Card className={styles.resultCard}>
                        <div className={styles.resultHeader}>
                            <span className={styles.resultIcon}>
                                {getResultInfo(scanResult).icon}
                            </span>
                            <span className={styles.resultType}>
                                {getResultInfo(scanResult).type}
                            </span>
                        </div>
                        <div className={styles.resultContent}>
                            {scanResult}
                        </div>
                    </Card>
                )}
            </Modal>
        </div>
    );
}

export default QRScanner; 